/*
 * @Author: taiyunhang
 * @Date: 2018-12-14 11:24:28
 * */

/**
 * 拦截器的配置
 */
import axios from 'axios';
// import qs from 'qs';
import router from '../routes';
import store from '@/store';
import { MessageBox, Toast } from 'mint-ui';
import LocalStorage from '@/services/storage';
import { requestCode } from '@/env';
import $ from 'jquery';
const proxy = require('@/env/proxy');
const proxyPath = proxy.proxyPath;
// const sourceCode = require('@/env');
// import proxyPath from '@/env/proxy';
// 创建实例时设置配置的默认值
const guid=()=>{
  function S4() {
	  return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
	}
  return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
};
const service = axios.create({
  baseURL: proxyPath,
  /* headers: {
    'Content-Type': 'application/json; charset=UTF-8'
  }, */
  headers: {
    'Content-Type': 'application/json; charset=UTF-8',
    'Accept': 'application/json, text/javascript, */*; q=0.01',
  },
  responseType: 'json',
  timeout: 1000 * 60, // 请求超时的时间
  // 对响应的数据进行处理
  transformResponse: [
    function(data) {
      return data;
      // return JSON.parse(data);
    }
  ],
  // 对请求的数据进行处理
  transformRequest: [
    function(data) {
      let token = LocalStorage.getLocalStorage('token');
      let loginStatus = LocalStorage.getLocalStorage('loginStatus');
      // data && (data["body"].sourceCode = sourceCode.sourceCode);
      data && token && (data["head"].token = token);
      data && loginStatus && (data["body"].matrixContent = loginStatus);
      // return JSON.stringify(data);
      // return qs.stringify(data);
      if(!token){
        if(loginStatus){
          if(data.body && data.body.needToken){
          
              var _obj = {
                "body":{
                  "matrixContent": loginStatus,
                  "abc":"22222"
                },
                "head":{
                  "requestCode": requestCode,
                  "serialno": guid()
                },
              };
              $.ajax({
                url:proxyPath+'user/removeLogin',//url路径
                type:'POST', //GET
                async:false, //或false,是否异步
                data:JSON.stringify(_obj),
                contentType:"application/json; charset=UTF-8",
                timeout:5000, //超时时间
                dataType:'json', //返回的数据格式：
                beforeSend:function(xhr){
                },
                success:function(res){
                  if (res.head.resultCode == "000000") {
                    let token2 = res.head.token;
                    data["head"].token = token2
                    LocalStorage.setLocalStorage(
                      "token",
                      token2,
                      59 * 60 * 1000
                    );
                  }
                },
                error:function(xhr,textStatus){
                },
                complete:function(data){
                }
            })


            // 
          }
        }
        
      }
      return JSON.stringify(data);
    }
  ]
});

// 请求拦截器
service.interceptors.request.use(
  config => {
    
    
    // 请求前的回调函数
    // if (store.state.token) {
    //   config.headers['access_token'] = store.state.token;
    // }

    
    // var token = LocalStorage.getLocalStorage('token');
    // if(!token){
    //   // MessageBox.alert(
    //   //   '会话过期!'
    //   // ).then(action => {
    //   //   if (action === 'confirm') {
    //   //     router.push({ path: '/' });
    //   //   }
    //   // });
    //   router.push({ path: '/' });
    // }else{
      store.dispatch('openLoading');
    // }
    
    return config;
  },
  err => {
    setTimeout(() => {
      store.dispatch('closeLoading');
    }, 50);
    Toast({ message: '加载超时', position: 'middle' });
    return Promise.reject(err);
  }
);

// 响应拦截器
service.interceptors.response.use(
  res => {
    if (res) {
      let data = res.data.head;
      console.log(data)
      // 非登录 -- 路由重定向
      if (data && data.resultCode && data.resultCode !== 'SUCCESS' && data.resultCode !== 'REFUND_SUCCESS') {
        setTimeout(() => {
          store.dispatch('closeLoading');
        }, 50);
        if (data.resultCode === '000001') {
          let loginStatus = LocalStorage.getLocalStorage('loginStatus');
          let openid = LocalStorage.getLocalStorage('openid');
          if(loginStatus){
            var _obj = {
              "head":{
                "requestCode": requestCode,
                "serialno": guid()
             },
             "body":{
                 "matrixContent":loginStatus
             }
            };
            axios.post(proxyPath+'user/removeLogin', _obj).then(function(res) {
              let head = res.data.head;
              if(head.resultCode=="000000"){
                let _token=head.token;
                LocalStorage.setLocalStorage(
                  "token",
                  _token,
                  59 * 60 * 1000
                );
              }else{
                setTimeout(()=> {
                  store.dispatch('logout');
                  router.push({ path: '/login' });
                },1000)
              }
              
            })
          }else if(openid){
            var _obj = {
              "head":{
                "requestCode": requestCode,
                "serialno": guid()
             },
             "body":{
                 "openId":openid
             }
            };
            axios.post(proxyPath+'user/removeLogin', _obj).then(function(res) {
              let head = res.data.head;
              if(head.resultCode=="000000"){
                let _token=head.token;
                LocalStorage.setLocalStorage(
                  "token",
                  _token,
                  59 * 60 * 1000
                );
              }else{
                setTimeout(()=> {
                  store.dispatch('logout');
                  router.push({ path: '/login' });
                },1000)
              }
              
            })
          }else{
            setTimeout(()=> {
              store.dispatch('logout');
              router.push({ path: '/login' });
            },1000)
          }
          
          
        }
        // if (data.resultCode && data.resultCode != 'REFUND_ERROR') {
        //   Toast({ message: data.resultMsg, position: 'middle' });
        // } else {
        //   MessageBox.alert(data.resultMsg);
        // }
        // throw Error(data.resultMsg);
      }
    }
    return res;
  },
  err => {
    console.log(err);
    setTimeout(() => {
      store.dispatch('closeLoading');
    }, 50);
    if (err.response) {
      switch (err.response.status) {
        case 401:
          // 返回 401 清除token信息并跳转到登录页面
          store.dispatch('logout');
          router.replace({
            path: 'login',
            query: { redirect: router.currentRoute.fullPath }
          });
      }
    }
    Toast({ message: '服务器有事离开一下，马上就回来', position: 'middle' });
    return Promise.reject(err);
  }
);

export default service;
